package com.yangyu.service;

import com.yangyu.mapper.MessageMapper;
import com.yangyu.mapper.UserMapper;
import com.yangyu.message.BaseRsp;
import com.yangyu.pojo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author
 * @version V1.0
 * @Package com.yangyu.service
 * @date 2021/1/13 20:40
 */
@Service
public class MessageService {

    @Autowired
    private MessageMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 添加留言
     *
     * @param message
     * @return
     */
    public BaseRsp addComment(Message message) {
        String id = UUID.randomUUID().toString();
        message.setId(id);
        message.setCreateTime(new Date());
        commentMapper.addMessage(message);
        Message commentById = commentMapper.getMessageById(id);
        return new BaseRsp(commentById);
    }

    /**
     * 查询评论
     *
     * @param
     * @return
     */
    public BaseRsp getCommentByBlogId() {
        BaseRsp rsp = new BaseRsp();

        // 根据博客id查询一级评论
        List<Message> comments = commentMapper.getMessage();
        if (CollectionUtils.isEmpty(comments)) {
            rsp.setData(new ArrayList<Message>(0));
            return rsp;
        }

        // 迭代查询一级评论下的子评论
        comments.forEach(comment -> {
            List<Message> childComments = commentMapper.getComment(comment.getId());
            if (CollectionUtils.isEmpty(childComments)) {
                comment.setChildComments(new ArrayList<>(0));
                return;
            }
            comment.setChildComments(childComments);
        });
        rsp.setData(comments);
        return rsp;
    }
}
